package com.itheima.aop;

import com.itheima.domain.pojo.OperateLog;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.utils.ThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Slf4j
@Component
public class OpLogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Pointcut("@annotation(com.itheima.annotation.OpLog)")
    public void pt(){}
    @Around("pt()")
    public Object recordLog(ProceedingJoinPoint pjp) throws Throwable {
        //操作时间
        LocalDateTime operateTime = LocalDateTime.now();
        //执行方法的全类名
        String className = pjp.getTarget().getClass().getName();
        //执行方法名
        String methodName = pjp.getSignature().getName();
        //方法的参数
        Object[] methodParams = pjp.getArgs();
        //获取当前登录用户的id/操作人的id
        Integer id = ThreadLocalUtils.get();
        //方法执行时长
        long startTime = System.currentTimeMillis();

        Object result= null;
        try {
            result = pjp.proceed();
            return result;
        } finally {String returnValue = (result != null) ? result.toString() : "void or null";
            long endTime = System.currentTimeMillis();
            long costTime = endTime - startTime;
            //封装对象
            OperateLog operateLog = new OperateLog(null,id,operateTime,className,methodName, Arrays.toString(methodParams),returnValue,costTime,null);
            //记录到数据库
            operateLogMapper.insertOpLog(operateLog);


        }
    }
}
